<?php

class DeleteAction extends CAction
{
    public function run()
    {
        if(!Yii::app()->request->isPostRequest || !isset($_POST['id']))
            throw new CHttpException(400,'the request is invalid');
                
        $recipe=Recipe::loadObjectById($_POST['id'],array('status','image','steps'));
        if($recipe===null)
            throw new CHttpException(404,'The requested recipe does not exist.');
        if($recipe->userId!=Yii::app()->user->id)
            throw new CHttpException(403,'cannot edit the recipe not belong to you');

        $steps=Step::loadObjectsByRecipeId($recipe->id);
        $succ=Recipe::deleteObject($recipe);
        if($succ) {
            foreach($steps as $step) {
                UserImage::delete('step', $step->image);            
            }
            UserImage::delete('recipe', $recipe->image);
            $redirectUrl=CHtml::normalizeUrl(array('list','id'=>$recipe->userId));
        }
        else {
            $error='删除失败';
        }

        $this->controller->renderPartial('/common/json',array(
            'data'=>array(
                'succ'=>$succ,
                'error'=>$error,
                'redirectUrl'=>$redirectUrl,
        )));
    }
}

?>